import axios from 'axios';

// 获取所有设备的最新状态
export const getLatestEquipmentStatus = async () => {
  const token = localStorage.getItem('token');
  return axios.get('https://penglink.pcwxcn.top/api/equipment/latest', {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    }
  });
};

// 更新当前设备的在线状态
export const updateDeviceOnlineStatus = async (currentDevice, deviceStore) => {
  if (!currentDevice) return;
  
  try {
    // 调用获取最新设备状态的API
    const response = await getLatestEquipmentStatus();
    
    if (response.status === 200 && response.data.code === 200) {
      const equipmentList = response.data.data || [];
      
      // 查找当前设备的状态信息
      const deviceNumber = currentDevice.device_number || currentDevice.id.toString();
      const equipmentStatus = equipmentList.find(item => 
        item.equipment_number === deviceNumber || 
        item.equipment_number === currentDevice.id.toString()
      );
      
      if (equipmentStatus) {
        // 更新设备状态
        const updatedDevice = {
          ...currentDevice,
          onlineStatus: equipmentStatus.auth || '下线',
          auth: equipmentStatus.auth || '下线'
        };
        
        // 更新当前设备状态
        deviceStore.setCurrentDevice(updatedDevice);
        console.log('设备在线状态已更新:', updatedDevice.onlineStatus);
        return updatedDevice;
      }
    }
  } catch (error) {
    console.error('获取设备实时状态失败:', error);
  }
  
  return null;
};

// 定期更新设备状态
export const startDeviceStatusPolling = (currentDevice, deviceStore, interval = 60000) => {
  // 立即更新一次
  updateDeviceOnlineStatus(currentDevice, deviceStore);
  
  // 设置定时器定期更新
  const timerId = setInterval(() => {
    updateDeviceOnlineStatus(currentDevice, deviceStore);
  }, interval);
  
  // 返回定时器ID，以便后续可以清除
  return timerId;
};

// 停止定期更新
export const stopDeviceStatusPolling = (timerId) => {
  if (timerId) {
    clearInterval(timerId);
  }
};